import tkinter as tk
import threading
from tkinter import messagebox, ttk
from functions import MealReminder
from wxauto_utils import bind_wechat

class SkyMealApp:
    def __init__(self):
        self.root = tk.Tk()
        try:
            self.root.iconbitmap("1.ico")  # 设置窗口图标
        except:
            pass  # 如果图标文件不存在则忽略
        self.reminder = MealReminder(self.root)
        self._init_variables()
        self._setup_ui()
        self.is_registered = False

    def _init_variables(self):
        """初始化所有界面变量"""
        self.time_vars = [tk.BooleanVar(value=False) for _ in range(7)]
        self.custom_time_var = tk.BooleanVar(value=False)
        self.custom_hour_var = tk.StringVar(value="00")
        self.custom_minute_var = tk.StringVar(value="00")
        self.spinbox_var = tk.IntVar(value=5)
        self.redstone_reminder_var = tk.BooleanVar(value=False)
        self.auto_close_var = tk.IntVar(value=0)
        self.wechat_reminder_var = tk.BooleanVar(value=False)  # 新增微信提醒变量
        self.wechat_target_name = ""  # 微信目标名称
        self.wechat_is_group = False  # 是否为群组

    def _setup_ui(self):
        """主界面布局"""
        self.root.title("干饭小助手v0.6")
        self.root.geometry("600x230")
        self._create_left_panel()
        self._create_right_panel()

    def _create_left_panel(self):
        """左侧时间选择面板"""
        left_frame = tk.Frame(self.root)
        left_frame.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.Y, expand=True)
        
        tk.Label(left_frame, text="选择干饭时间：").pack()
        time_labels = ["8点", "10点", "12点", "16点", "18点", "20点", "22点"]
        for var, label in zip(self.time_vars, time_labels):
            tk.Checkbutton(left_frame, text=label, variable=var).pack(anchor='w')

    def _create_right_panel(self):
        """右侧功能面板"""
        right_frame = tk.Frame(self.root)
        right_frame.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.Y, expand=True)
        
        self._create_custom_time(right_frame)
        self._create_advance_reminder(right_frame)
        self._create_redstone_reminder(right_frame)
        self._create_auto_close(right_frame)
        self._create_wechat_reminder(right_frame)  # 新增微信提醒控件
        self._create_buttons(right_frame)

    def _create_custom_time(self, parent):
        """自定义时间控件"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        
        tk.Label(frame, text="自定义时间 (HH:MM):").pack(side=tk.LEFT)
        tk.Checkbutton(frame, text="启用", variable=self.custom_time_var).pack(side=tk.LEFT)
        
        hours = [f"{i:02d}" for i in range(24)]
        ttk.Combobox(frame, textvariable=self.custom_hour_var, values=hours, width=3).pack(side=tk.LEFT)
        tk.Label(frame, text=":").pack(side=tk.LEFT)
        
        minutes = [f"{i:02d}" for i in range(60)]
        ttk.Combobox(frame, textvariable=self.custom_minute_var, values=minutes, width=3).pack(side=tk.LEFT)

    def _create_advance_reminder(self, parent):
        """提前提醒控件"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        
        tk.Label(frame, text="提前几分钟提醒：").pack(side=tk.LEFT)
        tk.Spinbox(frame, from_=0, to=60, textvariable=self.spinbox_var, width=5).pack(side=tk.LEFT)

    def _create_redstone_reminder(self, parent):
        """红石提醒控件"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        tk.Checkbutton(frame, text="红石提醒", variable=self.redstone_reminder_var).pack(side=tk.LEFT)

    def _create_auto_close(self, parent):
        """自动关闭控件"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        
        tk.Label(frame, text="自动关闭弹窗（秒）：").pack(side=tk.LEFT)
        tk.Spinbox(frame, from_=30, to=3600, textvariable=self.auto_close_var, width=5).pack(side=tk.LEFT)

    def _create_wechat_reminder(self, parent):
        """微信提醒控件"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        tk.Checkbutton(frame, text="微信提醒", variable=self.wechat_reminder_var).pack(side=tk.LEFT)

    def _create_buttons(self, parent):
        """按钮组"""
        frame = tk.Frame(parent)
        frame.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5)
        
        self.ok_button = tk.Button(frame, text="确定", command=self._on_ok)
        self.ok_button.pack(side=tk.LEFT, padx=10, expand=True)
        tk.Button(frame, text="确定并隐藏", command=self._on_ok_and_hide).pack(side=tk.LEFT, padx=10, expand=True)
        tk.Button(frame, text="设置微信目标", command=self._setup_wechat_target).pack(side=tk.LEFT, padx=10, expand=True)
        tk.Button(frame, text="退出程序", command=self.root.destroy).pack(side=tk.LEFT, padx=10, expand=True)

    def _setup_wechat_target(self):
        """设置微信提醒目标"""
        from wxauto_utils import load_wechat_targets, save_wechat_targets
        
        dialog = tk.Toplevel(self.root)
        dialog.title("微信提醒目标管理")
        dialog.geometry("500x400")
        
        # 加载已有目标
        targets = load_wechat_targets()
        self.wechat_targets = targets
        
        # 顶部输入区域
        input_frame = tk.Frame(dialog)
        input_frame.pack(pady=10)
        
        tk.Label(input_frame, text="目标名称:").grid(row=0, column=0, padx=5)
        target_entry = tk.Entry(input_frame, width=20)
        target_entry.grid(row=0, column=1, padx=5)
        
        target_type = tk.StringVar(value="friend")
        tk.Radiobutton(input_frame, text="好友", variable=target_type, value="friend").grid(row=0, column=2, padx=5)
        tk.Radiobutton(input_frame, text="群组", variable=target_type, value="group").grid(row=0, column=3, padx=5)
        
        # 目标显示区域
        display_frame = tk.Frame(dialog)
        display_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 好友列表
        tk.Label(display_frame, text="好友列表:").grid(row=0, column=0, sticky="w")
        friends_list = tk.Listbox(display_frame, width=25, height=8)
        friends_list.grid(row=1, column=0, padx=5, pady=5, sticky="nsew")
        for friend in targets["friends"]:
            friends_list.insert(tk.END, friend)
            
        # 群组列表
        tk.Label(display_frame, text="群组列表:").grid(row=0, column=1, sticky="w")
        groups_list = tk.Listbox(display_frame, width=25, height=8)
        groups_list.grid(row=1, column=1, padx=5, pady=5, sticky="nsew")
        for group in targets["groups"]:
            groups_list.insert(tk.END, group)
        
        # 按钮区域
        button_frame = tk.Frame(dialog)
        button_frame.pack(pady=10)
        
        def add_target():
            name = target_entry.get()
            if not name:
                messagebox.showwarning("警告", "请输入目标名称")
                return
                
            if target_type.get() == "friend":
                if name not in targets["friends"]:
                    targets["friends"].append(name)
                    friends_list.insert(tk.END, name)
            else:
                if name not in targets["groups"]:
                    targets["groups"].append(name)
                    groups_list.insert(tk.END, name)
            
            target_entry.delete(0, tk.END)
            save_wechat_targets(targets)
            
        def delete_target():
            selected = friends_list.curselection()
            if selected:
                name = friends_list.get(selected[0])
                targets["friends"].remove(name)
                friends_list.delete(selected[0])
                save_wechat_targets(targets)
                return
                
            selected = groups_list.curselection()
            if selected:
                name = groups_list.get(selected[0])
                targets["groups"].remove(name)
                groups_list.delete(selected[0])
                save_wechat_targets(targets)
        
        def on_confirm():
            dialog.destroy()
            
        tk.Button(button_frame, text="添加", command=add_target).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="删除", command=delete_target).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="确定", command=on_confirm).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="关闭", command=dialog.destroy).pack(side=tk.LEFT, padx=5)

    def _on_ok(self):
        """确定按钮事件"""
        if self.is_registered:
            # 取消功能
            self.reminder.stop()
            self.ok_button.config(text="确定")
            self.is_registered = False
            messagebox.showinfo("提示", "提醒服务已取消！")
            return
            
        # 禁用按钮防止重复点击
        self.ok_button.config(state=tk.DISABLED)
        
        def async_start():
            try:
                selected_times = [int(label.split('点')[0]) for var, label in zip(self.time_vars, ["8点","10点","12点","16点","18点","20点","22点"]) if var.get()]
                custom_time = (int(self.custom_hour_var.get()), int(self.custom_minute_var.get())) if self.custom_time_var.get() else None
                
                if not selected_times and not custom_time:
                    self.root.after(0, lambda: messagebox.showwarning("警告", "请至少选择一个时间点或输入自定义时间"))
                    return
                
                # 确保传递微信提醒选项
                self.reminder.main_root.wechat_reminder_var = self.wechat_reminder_var
                
                # 启动服务
                self.reminder.start(
                    selected_times=selected_times,
                    custom_time=custom_time,
                    advance_minutes=self.spinbox_var.get(),
                    auto_close_seconds=self.auto_close_var.get(),
                    redstone_enabled=self.redstone_reminder_var.get()
                )
                
                # 微信提醒处理
                if self.wechat_reminder_var.get():
                    from wxauto_utils import load_wechat_targets
                    targets = load_wechat_targets()
                    
                    if not targets["friends"] and not targets["groups"]:
                        self.root.after(0, lambda: messagebox.showwarning("警告", "请先添加微信提醒目标"))
                        return
                    
                    wx = bind_wechat()
                    if wx:
                        self.root.after(0, lambda: messagebox.showinfo("提示", "微信绑定成功！"))
                        from wxauto_utils import send_wechat_message
                        for friend in targets["friends"]:
                            send_wechat_message(
                                wx,
                                friend,
                                "干饭小助手已启动，将按时提醒您用餐和红石时间！",
                                False
                            )
                        for group in targets["groups"]:
                            send_wechat_message(
                                wx,
                                group,
                                "干饭小助手已启动，将按时提醒您用餐和红石时间！",
                                True
                            )
                
                # 更新UI
                self.root.after(0, lambda: [
                    messagebox.showinfo("提示", "干饭时间已登记！"),
                    self.ok_button.config(text="取消", state=tk.NORMAL),
                    setattr(self, 'is_registered', True)
                ])
                
            except Exception as e:
                self.root.after(0, lambda: [
                    messagebox.showerror("错误", f"启动服务失败: {str(e)}"),
                    self.ok_button.config(state=tk.NORMAL)
                ])
        
        # 在新线程中执行耗时操作
        threading.Thread(target=async_start, daemon=True).start()

    def _on_ok_and_hide(self):
        """确定并隐藏按钮事件"""
        self._on_ok()
        self.root.withdraw()

    def run(self):
        """运行主循环"""
        self.root.mainloop()

if __name__ == "__main__":
    app = SkyMealApp()
    app.run()
